<?php

namespace App\Http\Controllers\Admin\Article;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\ArticleCategory;
use App\Models\Product;
use App\Traits\Controllers\AdminTraits;
use App\Traits\Controllers\UpdateStatusTraits;
use App\Traits\Controllers\UpdateTraits;
use App\Transformers\Article\ArticlesTransformer;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    //文章的增删改查
    use AdminTraits;
    use UpdateStatusTraits;

    //定义模型和transformer
    public $model = Article::class;
    public $transformer = ArticlesTransformer::class;


    /**
     * 参数验证规则
     *
     * @param Request $request
     * @return array
     */
    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return [
                    'title' => 'required|min:6|max:16',
                    'category_id' => 'required',
                    'image_input' => 'required',
                    'content' => 'required|min:10|max:255',
                ];
                break;
        }
        return [

        ];
    }


    public function ruleMessages(): array
    {
        return [
            'title.required' => '标题 不能为空',
            'title.min' => '标题 必须至少包含6个字段',
            'title.max' => '标题 最多包含16个字段',
            'category_id.required' => '文章分类 不能为空',
            'image_input.required' => '文章图片 不能为空',
            'content.required' => '文章内容 不能为空',
            'content.min' => '文章内容 最少10个字段',
            'content.max' => '文章内容 最多255个字段',
        ];
    }

    public function index(Request $request)
    {
        $data = $this->getQuery()
            ->pimp()
            ->with('product:id,product_name')
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->transformer));
    }

    //文章关联商品
    public function relation(Request $request){
        //判断request中是否有商品id和文章id
        $article_id = $request->input('article_id');
        $product_id = $request->input('product_id');
        if(empty($article_id)){
            return $this->response->errorBadRequest('没有文章，请选择文章');

        }
        if(empty($product_id)){
            return $this->response->errorBadRequest('没有商品，请选择商品');

        }
        //通过文章id拿到文章
        $article = Article::find($article_id);
        $article->product_id = $request->input('product_id');
        $article->save();
        return $this->response->noContent();

    }

    //文章取消关联商品
    public function unrelation(Article $article){
        //判断request中有没有文章的id
        $article->product_id = 0;
        $article->save();
        $this->response->noContent();
      }
}




